package cn.com.shopec.erp.stock.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.com.shopec.erp.base.service.impl.SupplierInfoService;
import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.excel.ExcelBaseExport;
import cn.com.shopec.erp.common.page.PageFinder;
import cn.com.shopec.erp.common.page.PageQuery;
import cn.com.shopec.erp.financing.service.IWhareHouseServer;
import cn.com.shopec.erp.multiChannel.service.IChannelOrderService;
import cn.com.shopec.erp.multiChannel.vo.ChannelOrderVo;
import cn.com.shopec.erp.product.service.IDefectReplceService;
import cn.com.shopec.erp.product.vo.DefectReplceVo;
import cn.com.shopec.erp.purchase.service.IPurchaseOrderService;
import cn.com.shopec.erp.stock.commo.JsonUtil;
import cn.com.shopec.erp.stock.commo.StockInUtil;
import cn.com.shopec.erp.stock.entity.StockInProduct;
import cn.com.shopec.erp.stock.excel.impl.StockInExcelExport;
import cn.com.shopec.erp.stock.service.IStockHistoryService;
import cn.com.shopec.erp.stock.service.IStockInService;
import cn.com.shopec.erp.stock.service.IStockOutService;
import cn.com.shopec.erp.stock.service.impl.StockInServiceImpl;
import cn.com.shopec.erp.stock.vo.StockInProductVo;
import cn.com.shopec.erp.stock.vo.StockInVo;
import cn.com.shopec.erp.stock.vo.StockOutProductVo;
import cn.com.shopec.erp.warehouse.vo.StockTransferVo;

@Controller
@RequestMapping("stockmanage/StockController")
public class StockInController {

	@Resource
	private IStockHistoryService stockHistoryService;

	/** 日志. */
	private Logger log = Logger.getLogger(StockInServiceImpl.class);

	@Resource
	private IStockOutService stockOutService;

	@Resource
	private IPurchaseOrderService poService;

	@Resource
	private IStockInService stockInService;

	@Resource
	private IWhareHouseServer iWhareHouseServer;

	@Resource
	private SupplierInfoService supplierInfoService;

	@Resource
	private IChannelOrderService channelOrderService;

	@Resource
	IDefectReplceService defectReplceService;

	/**
	 * 跳转到入库查询页面
	 * 
	 * @param stockIn
	 * @param pageQuery
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("pageFinderStockIn")
	public String pageFinderStockInPackage(StockInVo stockIn, PageQuery pageQuery, ModelMap map) throws Exception {
		map.put("stockIn", stockIn);
		map.put("whareHouse", iWhareHouseServer.getAllWhareHouse());
		return "/stock/stockIn_info_list";
	}

	/**
	 * 导出excel
	 * 
	 * @param stockIn
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("exportStockIn")
	public void exportStockInPackage(StockInVo stockIn, HttpServletResponse response) throws Exception {
		List<StockInVo> list = stockInService.queryStockListByFinder(stockIn);
		ExcelBaseExport excelBaseExport = new StockInExcelExport(list, "商品入库信息_" + System.currentTimeMillis(),
				response);
		try {
			excelBaseExport.wirteExcel();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 分页查询入库
	 * 
	 * @param stockIn
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("ajaxPageFinderStockIn")
	@ResponseBody
	public String ajaxPageFinderStockInPackage(StockInVo stockIn, PageQuery pageQuery, ModelMap map) {
		JSONObject jsonObj = new JSONObject();
		PageFinder<StockInVo> pageFinder = stockInService.queryStockList(stockIn, pageQuery);
		jsonObj.put("Rows", pageFinder.getData());
		jsonObj.put("Total", pageFinder.getRowCount());
		return jsonObj.toJSONString();
	}

	/**
	 * 分页查询入库商品
	 * 
	 * @param stockIn
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("ajaxPageFinderStockInDetail")
	@ResponseBody
	public String ajaxPageFinderStockInDetailPackage(StockInVo stockIn, PageQuery pageQuery, ModelMap map) {
		JSONObject jsonObj = new JSONObject();
		PageFinder<StockInProductVo> pageFinder = stockInService.queryStockProductList(stockIn, pageQuery);
		jsonObj.put("Rows", pageFinder.getData());
		jsonObj.put("Total", pageFinder.getRowCount());
		return jsonObj.toJSONString();
	}

	/**
	 * 跳转到入库详情查询页面
	 * 
	 * @param stockIn
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("toStockInDetail")
	public String pageFinderStockInDetailPackage(String tabId, String stockInNo, ModelMap map) {
		map.put("stockIn", stockInService.getStockByNo(stockInNo));
		map.put("stockInViewType", SZSCMConstant.STOCK_INFO_VIEW);
		map.put("tabId", tabId);
		return "/stock/stockIn_detail";
	}

	/**
	 * 删除入库
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("deleteStockInProduct")
	@ResponseBody
	public String deleteStockInProduct(String id) {
		try {
			if (stockInService.deleteStockInProduct(id)) {
				return SZSCMConstant.SUCCESS;
			}
		} catch (Exception e) {
			log.error("deleteStockInProduct" + e.getMessage(), e);
		}
		return SZSCMConstant.FAIL;
	}

	@RequestMapping("toAddStockIn")
	public String toAddStockIn(ModelMap map) throws Exception {
		map.put("stockInViewType", 1);
		map.put("whareHouse", iWhareHouseServer.getAllWhareHouse());
		return "/stock/stockIn_detail";
	}

	// /**
	// * 新增入库信息
	// *
	// * @param stockIn
	// * @param products
	// * @param map
	// * @return
	// */
	// @RequestMapping("addStockIn")
	// @ResponseBody
	// public String addStockIn(StockIn stockIn, String products, ModelMap map)
	// {
	// try {
	// @SuppressWarnings("unchecked")
	// List<StockInProduct> stockInProducts = (List<StockInProduct>)
	// JsonUtil.changeJsonToList(products,
	// StockInProduct.class);
	// stockInService.addStockIn(stockIn, stockInProducts);
	// return SZSCMConstant.SUCCESS;
	// } catch (Exception e) {
	// log.error("addStockInfo" + e.getMessage(), e);
	// }
	// return SZSCMConstant.FAIL;
	// }

	/**
	 * 跳转到入库审核页面
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toStockInApprove")
	public String toApproveStockIn(String stockInNo, String tabId, PageQuery pageQuery, ModelMap map) throws Exception {
		StockInVo stockIn = stockInService.getStockByNo(stockInNo);
		if (!StringUtils.isEmpty(stockInNo)) {
			map.put("stockIn", stockIn);
		}
		map.put("tabId", tabId);
		map.put("stockInViewType", SZSCMConstant.STOCK_AUDIT_VIEW);
		return "/stock/stockIn_detail";
	}

	/**
	 * 入库审核
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("approveStockIn")
	@ResponseBody
	public String approveStockIn(StockInVo stockInVo, String products, ModelMap map) {
		boolean result = false;
		try {
			@SuppressWarnings("unchecked")
			List<StockInProductVo> stockInProducts = (List<StockInProductVo>) JsonUtil.changeJsonToList(products,
					StockInProductVo.class);
			if(stockInVo.getStockInType().equals(SZSCMConstant.STOCKIN_TYPE_5)){
				result = stockInService.approveStockInForTransfer(stockInVo, stockInProducts);
			}else{
				result = stockInService.approveStockIn(stockInVo, stockInProducts);
			}
		} catch (Exception e) {
			log.error("approveStockIn" + e.getMessage(), e);
		}
		return result ? SZSCMConstant.SUCCESS : SZSCMConstant.FAIL;
	}

	// ---------------------------采购入库相关
	/**
	 * 新增入库信息（采购用）
	 * 
	 * @param stockIn
	 * @param products
	 * @param map
	 * @return
	 */
	@RequestMapping("addStockInForPurchaseOrder")
	@ResponseBody
	public String addStockInForPurchaseOrder(StockInVo stockIn, String products, ModelMap map) {
		try {
			@SuppressWarnings("unchecked")
			List<StockInProductVo> stockInProducts = (List<StockInProductVo>) JsonUtil.changeJsonToList(products,
					StockInProductVo.class);
			stockInService.addStockIns(stockIn, stockInProducts);
			return SZSCMConstant.SUCCESS;
		} catch (Exception e) {
			log.error("addStockInForPurchaseOrder" + e.getMessage(), e);
		}
		return SZSCMConstant.FAIL;
	}

	// ---------------------------订单入库相关
	/**
	 * 跳转订单退换货生成入库单页面
	 * 
	 * @param channelOrderVo
	 * @param pageQuery
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toStockInAddForBookBill")
	public String toPackageStockIn(String channelOrderId, String tabId, ModelMap map) throws Exception {
		JSONObject jsonObj = new JSONObject();
		try {
			StockInVo stockIn = new StockInVo();
			// stockIn.setStockInNo(NoUtil.getNo(NoUtil.STOCKIN_NO));
			stockIn.setStockInType(SZSCMConstant.STOCKIN_TYPE_2);
			stockIn.setStockInTypeNo(channelOrderId);
			jsonObj.put("data", iWhareHouseServer.getAllWhareHouse());
			map.put("stockIn", stockIn);
		} catch (Exception e) {
			log.error("toStockInAddForBookBill" + e.getMessage(), e);
		}
		map.put("whareHouses", jsonObj.toJSONString());
		map.put("stockInViewType", SZSCMConstant.STOCK_BOOKBILL_VIEW);
		map.put("tabId", tabId);
		return "/stock/stockIn_detail";
	}

	/**
	 * 获取订单退货商品商品，并转成入库单商品返回
	 * 
	 * @param channelOrderVo
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("getBookReturnProduct")
	@ResponseBody
	public String getPackageProduct(ChannelOrderVo channelOrderVo, PageQuery pageQuery, ModelMap map) {
		JSONObject jsonObj = new JSONObject();
		if (!StringUtils.isEmpty(channelOrderVo.getChannelOrderId())) {
			@SuppressWarnings("unchecked")
			PageFinder<Map<String, Object>> pageFinder = channelOrderService.returnOrderItemPageList(channelOrderVo,
					pageQuery);
			List<StockInProductVo> stockInProductVo = StockInUtil
					.parseStockInProductVoForChannelOrder(pageFinder.getData());
			jsonObj.put("Rows", stockInProductVo);
			jsonObj.put("Total", pageFinder.getRowCount());
		}
		return jsonObj.toJSONString();
	}

	/**
	 * 新增入库信息（订单退货用）
	 * 
	 * @param stockIn
	 * @param products
	 * @param map
	 * @return
	 */
	@RequestMapping("addStockInForBookReturnBill")
	@ResponseBody
	public String addStockInForBookReturnBill(StockInVo stockIn, String products, ModelMap map) {
		try {
			@SuppressWarnings("unchecked")
			List<StockInProductVo> stockInProducts = (List<StockInProductVo>) JsonUtil.changeJsonToList(products,
					StockInProductVo.class);
			stockInService.addStockIns(stockIn, stockInProducts);
			return SZSCMConstant.SUCCESS;
		} catch (Exception e) {
			log.error("addStockInForBookReturnBill" + e.getMessage(), e);
		}
		return SZSCMConstant.FAIL;
	}

	// ---------------------------次品入库相关
	/**
	 * 跳转次品换货生成入库单页面
	 * 
	 * @param channelOrderVo
	 * @param pageQuery
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toDefectReplceStockIn")
	public String toDefectReplceStockIn(DefectReplceVo defectReplceVo, String tabId, ModelMap map) throws Exception {
		JSONObject jsonObj = new JSONObject();
		try {
			defectReplceVo = defectReplceService.getPurchaseOrder(defectReplceVo.getDefectReplceId());
			StockInVo stockIn = StockInUtil.parseStockIn(defectReplceVo);
			StockInProductVo stockInProductVo = StockInUtil.parseStockInProductVo(defectReplceVo);
			jsonObj.put("stockInProductVo", stockInProductVo);
			// stockIn.setStockInNo(NoUtil.getNo(NoUtil.STOCKIN_NO));
			stockIn.setStockInType(SZSCMConstant.STOCKIN_TYPE_3);
			// stockInProductVo.setStockInNo(stockIn.getStockInNo());
			map.put("stockInViewType", SZSCMConstant.STOCK_DEFECT_IN_VIEW);
			map.put("stockIn", stockIn);
			map.put("tabId", tabId);
			map.put("stockInProduct", jsonObj.toJSONString());
		} catch (Exception e) {
			log.error("toDefectReplceStockIn" + e.getMessage(), e);
		}
		return "/stock/stockIn_detail";
	}

	/**
	 * 新增入库信息（次品换货用）
	 * 
	 * @param stockIn
	 * @param products
	 * @param map
	 * @return
	 */
	@RequestMapping("addStockInForDefectReplce")
	@ResponseBody
	public String addStockInForDefectReplce(StockInVo stockIn, String products, ModelMap map) {
		try {
			@SuppressWarnings("unchecked")
			List<StockInProductVo> stockInProducts = (List<StockInProductVo>) JsonUtil.changeJsonToList(products,
					StockInProductVo.class);
			stockInService.addStockIns(stockIn, stockInProducts);
			return SZSCMConstant.SUCCESS;
		} catch (Exception e) {
			log.error("addStockInForPurchaseOrder" + e.getMessage(), e);
		}
		return SZSCMConstant.FAIL;
	}

	// ---------------------------采购换货入库相关
	/**
	 * 新增入库信息（采购换货用）
	 * 
	 * @param stockIn
	 * @param products
	 * @param map
	 * @return
	 */
	@RequestMapping("addStockInForPurReturnBill")
	@ResponseBody
	public String addStockInForPurReturnBill(StockInVo stockIn, String products, ModelMap map) {
		try {
			@SuppressWarnings("unchecked")
			List<StockInProductVo> stockInProducts = (List<StockInProductVo>) JsonUtil.changeJsonToList(products,
					StockInProductVo.class);
			stockInService.addStockIns(stockIn, stockInProducts);
			return SZSCMConstant.SUCCESS;
		} catch (Exception e) {
			log.error("addStockInForPurchaseOrder" + e.getMessage(), e);
		}
		return SZSCMConstant.FAIL;
	}

	// -------------调拨入库相关
	/**
	 * 跳转调拨生成入库单页面
	 * 
	 * @param channelOrderVo
	 * @param pageQuery
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toTransferStockIn")
	public String toTransferStockIn(StockTransferVo stockTransfer, String tabId, ModelMap map) throws Exception {
		try {
			StockInVo stockIn = new StockInVo();
			// stockIn.setStockInNo(NoUtil.getNo(NoUtil.STOCKIN_NO));
			stockIn.setStockInType(SZSCMConstant.STOCKIN_TYPE_5);
			stockIn.setStockInTypeNo(stockTransfer.getTransferNo());
			stockIn.setWhNo(stockTransfer.getTransferInWhNo());
			stockIn.setWhName(stockTransfer.getTransferInWhName());
			map.put("stockInViewType", SZSCMConstant.STOCK_TRANSFER_IN_VIEW);
			map.put("stockIn", stockIn);
			map.put("tabId", tabId);
		} catch (Exception e) {
			log.error("toDefectReplceStockIn" + e.getMessage(), e);
		}
		return "/stock/stockIn_detail";
	}

	/**
	 * 新增调拨信息
	 * 
	 * @param stockIn
	 * @param products
	 * @param map
	 * @return
	 */
	@RequestMapping("addStockInForTransfer")
	@ResponseBody
	public String addStockInForTransfer(StockInVo stockIn, String products, ModelMap map) {
		try {
			@SuppressWarnings("unchecked")
			List<StockInProduct> stockInProducts = (List<StockInProduct>) JsonUtil.changeJsonToList(products,
					StockInProduct.class);
			stockInService.addStockInForTransfer(stockIn, stockInProducts);
			return SZSCMConstant.SUCCESS;
		} catch (Exception e) {
			log.error("addStockInForTransfer" + e.getMessage(), e);
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 获取调拨出库的商品，并转成入库单商品返回
	 * 
	 * @param channelOrderVo
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("getTransferProduct")
	@ResponseBody
	public String getTransferProduct(StockInVo stockIn, PageQuery pageQuery, ModelMap map) {
		JSONObject jsonObj = new JSONObject();
		if (!StringUtils.isEmpty(stockIn.getStockInTypeNo())) {
			PageFinder<StockOutProductVo> pageFinder = stockOutService
					.queryStockProductListForTransfer(stockIn.getStockInTypeNo(), pageQuery);
			jsonObj.put("Rows", pageFinder.getData());
			jsonObj.put("Total", pageFinder.getRowCount());
		}
		return jsonObj.toJSONString();
	}
}
